<!--
 * @Author: fengshan0525 2735332396@qq.com
 * @Date: 2023-03-18 15:29:41
 * @LastEditors: asanupup 15465106+asanupup@user.noreply.gitee.com
 * @LastEditTime: 2025-07-22 17:10:28
 * @FilePath: \b-vue3-ts-ele-template\src\views\system\UsersManage.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryForm" ref="queryFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryForm.username" placeholder="用户名" clearable />
      </el-form-item>
    </el-form>
    <ActionButtons @reset="handleReset" @query="queryUserList"></ActionButtons>
    <el-button type="primary" size="small" @click="handleAddUser">新增用户</el-button>
    <BaseTable :table-columns="tableColumns" :table-data="tableData" :options="options" :page-size="page.pageSize"
      :page-num="page.pageNum" :total="page.total">
      <template v-slot:operation="{ row }">
        <el-button text type="primary" @click="handleEdit(row)">编辑</el-button>
        <el-button text style="color: red;" @click="handleDel(row)">删除</el-button>
      </template>
    </BaseTable>
    <Dialog ref="dialogRef" :title="dialogOptions.title" width="850px" @close="handleCancel" @confirm="handleConfirm">
      <template v-slot:content>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="ruleForm.nickName" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="ruleForm.username" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" type="password" :show-password="true" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="状态" prop="status">
            <el-switch v-model="ruleForm.status" active-value="1" inactive-value="0" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" />
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="ruleForm.telephone" />
          </el-form-item>
          <el-form-item label="角色" prop="roles">
            <el-select v-model="ruleForm.roles" multiple placeholder="角色">
              <el-option v-for="item in rolesList" :key="item.roleId" :label="item.roleName"
                :value="item.roleKey"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>
<script lang='ts' setup>
/* ------------------------------ variable ------------------------------ */
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import useHooksTable from '@/views/System/UsersManage/useHooksTable'
import useHooksAddUser from '@/views/System/UsersManage/useHooksAddUser'
import { resetForm, validateForm } from '@/utils/tools'
import FSMessage from '@/utils/message'
import { delUserAPI, createUser, updateUser } from '@/api/user'
import { queryRolesListAPI } from '@/api/roles'
import { cloneDeep } from 'lodash-es'
import md5 from 'md5'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()
const dialogRef = ref()

const { rules, ruleForm, dialogVisible, dialogOptions, rolesList } = useHooksAddUser()
const { tableColumns, tableData, options, queryUserList, page, queryForm } = useHooksTable()
/* ------------------------------ function ------------------------------ */
queryUserList()

const handleReset = () => {
  resetForm(queryFormRef.value)
  queryUserList()
}

const handleEdit = async (row) => {
  try {
    ruleForm.value = cloneDeep(row)
    dialogVisible.value = true
    dialogOptions.value.openType = 2
    dialogOptions.value.title = '编辑用户'
    if (!rolesList.value) {
      const res = await queryRolesListAPI({ ...page, roleName: '', roleKey: '', status: '1' })
      rolesList.value = res.data.list
    }
    dialogRef.value.visiableDialog()
  } catch (e) {
    console.log(e)
  }
}

const handleDel = (row) => {
  FSMessage.confirm('是否确认删除', '提示').then(() => {
    delUserAPI(row._id).then(() => {
      FSMessage.success('删除成功')
      queryUserList()
    })
  }).catch(e => {
    FSMessage.info('已取消删除')
  })
}

/**
 * 新增用户
 */
const handleAddUser = async () => {
  try {
    const res = await queryRolesListAPI({ ...page, roleName: '', roleKey: '', status: '1' })
    rolesList.value = res.data.list
    dialogRef.value.visiableDialog()
  } catch (e) {
    console.log(e)
  }
}

/**
* @description: 弹窗取消
* @return {*}
*/
const handleCancel = () => {
  dialogVisible.value = false
  ruleFormRef.value.clearValidate()
}

/**
 * @breif: 弹窗确认
 * @return {*}
 */
const handleConfirm = async () => {
  try {
    await validateForm(ruleFormRef.value)
    ruleForm.value.password = md5(ruleForm.value.password)
    dialogOptions.value.openType === 1 ? await createUser(ruleForm.value) : await updateUser(ruleForm.value)
    FSMessage.success(`${dialogOptions.value.openType === 1 ? '创建成功' : '修改成功'}`)
    queryUserList()
    dialogRef.value.invisiableDialog()
  } catch (e) {
    console.log(e)
  }
}
</script>
<style scoped lang='less'>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
